package com.plate.modules.system.controller;

import cn.hutool.core.util.StrUtil;
import com.plate.common.core.result.Result;
import com.plate.common.core.utils.StrUtils;
import com.plate.modules.system.domain.po.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;

/**
 * @ClassName SysCommonController
 * @Description TODO
 * @Author jiaxd
 * @Date 2023年11月25日 17:51
 * @Version 1.0
 */

@Slf4j
@RestController
@RequestMapping("sys/common")
public class SysCommonController {

    @Value("${uploadFile.base.dir}")
    private String ctxPath;

    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile multipartFile) {

        // 文件原名
        try {

            String filePath = "/" + LocalDate.now().getYear() + "/" + LocalDate.now().getMonthValue() + "/" + LocalDate.now().getDayOfMonth();
            File file = new File(ctxPath + filePath);
            if (!file.exists()) {
                // 创建文件根目录
                file.mkdirs();
            }
            String orgName = multipartFile.getOriginalFilename();
            String fileName = StrUtils.getRandomNumberString(16);
            String ext = orgName.substring(orgName.lastIndexOf(".") + 1).toLowerCase();
            String savePath = filePath + "/" + fileName + "." + ext;
            multipartFile.transferTo(new File(ctxPath + savePath));
            SysFile sysFile = new SysFile();
            sysFile.setFileName(fileName);
            sysFile.setOrigName(orgName);
            sysFile.setFilePath(filePath);
            sysFile.setSuffix(ext);
            sysFile.setSize(multipartFile.getSize());
            sysFile.setVersion("1");

            return Result.SUCCESS(savePath);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.FAIL();
        }

    }

//    @GetMapping(value = "/static/**")
//    public void view(HttpServletRequest request, HttpServletResponse response) {
//        String imgPath = extractPathFromPattern(request);
//        if(StrUtil.isEmpty(imgPath)){
//            return;
//        }
//        // 其余处理略
//        InputStream inputStream = null;
//        OutputStream outputStream = null;
//
//        try {
//            imgPath = imgPath.replace("..", "").replace("../","");
////            if (imgPath.endsWith(SymbolConstant.COMMA)) {
////                imgPath = imgPath.substring(0, imgPath.length() - 1);
////            }
//            //update-begin---author:liusq ---date:20230912  for：检查下载文件类型--------------
////            SsrfFileTypeFilter.checkDownloadFileType(imgPath);
//            //update-end---author:liusq ---date:20230912  for：检查下载文件类型--------------
//
//            String filePath = ctxPath + File.separator + imgPath;
//            File file = new File(filePath);
//            if(!file.exists()){
//                response.setStatus(404);
//                log.error("文件["+imgPath+"]不存在..");
//                return;
//                //throw new RuntimeException();
//            }
//            // 设置强制下载不打开
//            response.setContentType("application/octet-stream");
//            response.addHeader("Content-Disposition", "inline;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
//            inputStream = new BufferedInputStream(new FileInputStream(filePath));
//            outputStream = response.getOutputStream();
//            byte[] buf = new byte[1024];
//            int len;
//            while ((len = inputStream.read(buf)) > 0) {
//                outputStream.write(buf, 0, len);
//            }
//            response.flushBuffer();
//            response.setHeader("content-disposition", "inline");
//        } catch (IOException e) {
//            log.error("预览文件失败" + e.getMessage());
//            response.setStatus(404);
//            e.printStackTrace();
//        } finally {
//            if (inputStream != null) {
//                try {
//                    inputStream.close();
//                } catch (IOException e) {
//                    log.error(e.getMessage(), e);
//                }
//            }
//            if (outputStream != null) {
//                try {
//                    outputStream.close();
//                } catch (IOException e) {
//                    log.error(e.getMessage(), e);
//                }
//            }
//        }
//
//    }

    /**
     * 预览图片&下载文件
     * 请求地址：http://localhost:8080/common/static/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/static/**")
    public void view(HttpServletRequest request, HttpServletResponse response) {
        // ISO-8859-1 ==> UTF-8 进行编码转换
        String imgPath = extractPathFromPattern(request);
        if(StrUtil.isEmpty(imgPath)){
            return;
        }
        // 其余处理略
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            imgPath = imgPath.replace("..", "").replace("../","");

            String filePath = ctxPath + File.separator + imgPath;
            File file = new File(filePath);
            if(!file.exists()){
                response.setStatus(404);
                log.error("文件["+imgPath+"]不存在..");
                return;
            }
            // 设置强制下载不打开
            response.setContentType("image/jpeg;charset=utf-8");
//            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
            inputStream = new BufferedInputStream(new FileInputStream(filePath));
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (IOException e) {
            log.error("预览文件失败" + e.getMessage());
            response.setStatus(404);
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

    }

    /**
     *  把指定URL后的字符串全部截断当成参数
     *  这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }


}
